package com.villaday.idf.util;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Build;
import android.os.Handler;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.View;

import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import com.google.android.material.snackbar.Snackbar;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.villaday.idf.AppContext;
import com.villaday.idf.activity.LoginActivity;
import com.villaday.idf.model.BaseEntity;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLSession;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.Headers;
import okhttp3.HttpUrl;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okio.Buffer;
import okio.BufferedSink;
import okio.Okio;
import okio.Source;

/**
 * OkHttp的工具类
 */
public class OkHttpUtil {

    private static OkHttpClient okHttpClient;
    private static Handler handler = new Handler();
    private static Gson gson = new GsonBuilder().create();
    private static Context context;

    private static String DC_ID = "6";//渠道id  10 vivo  0 官网  6小米

    //AppId
    private static final String FORMAL_TRANSTAIONID = "bGMrkFcOlE1odiAX";//正式
    // private static final String FORMAL_TRANSTAIONID = "y6i3fLSDHrz8AhJa";//测试
    //其他
     private static final String FORMAL_TRANSTAION = "_bEg9VoG6TFPrjS34KCaZey8pwLUniqxd";//正式
    //   private static final String FORMAL_TRANSTAION = "_z1zJRdJh668keWxGpBd1LYj5rCsRANJw";//测试

    private static final String API_VERSION = "3.1";//正式

    public static void initOkHttp() {
        okHttpClient = new OkHttpClient.Builder()
                .connectTimeout(120, TimeUnit.MINUTES)
                .readTimeout(120, TimeUnit.MINUTES)
                .writeTimeout(120, TimeUnit.MINUTES)
                .addInterceptor(new RetryIntercepter(3))//重试
                .retryOnConnectionFailure(true)
                .sslSocketFactory(HttpsUtils.getSslSocketFactory(null, null, null))//创建一个证书对象
                .hostnameVerifier(new HostnameVerifier() {
                    @Override
                    public boolean verify(String s, SSLSession sslSession) {
                        return true;
                    }
                })//校验名称,这个对象就是信任所有的主机,也就是信任所有https的请求
                .build();
    }


    /**
     * query  GET
     */
    public static void getJSON(Context context, String url, Map<String, String> map, OnDataListener dataListener) {
        OkHttpUtil.context = context;
        DisplayMetrics displayMetrics = context.getResources().getDisplayMetrics();
        int width = displayMetrics.widthPixels;
        int height = displayMetrics.heightPixels;
        Map<String, String> inJson = new HashMap<>();

        for (Map.Entry<String, String> entry : map.entrySet()) {

            if (!TextUtils.isEmpty(entry.getValue())) {
                inJson.put(entry.getKey(), entry.getValue());
            }
        }
        // inJson.putAll(map);

        String signStrinf = "";
        String createRandom = PhoneUtil.createRandom(false, 32).toUpperCase();
        inJson.put("app-id", FORMAL_TRANSTAIONID);//测试y6i3fLSDHrz8AhJa//正式bGMrkFcOlE1odiAX
        inJson.put("app-bundle-version", PhoneUtil.getAppVersion(context));
        inJson.put("app-build-version", "0");
        inJson.put("x-api-version", API_VERSION);
       /* inJson.put("x-push-id", "76d8ee88646bd761f671fbff");
        inJson.put("x-push-type", "1");*/
        if (!TextUtils.isEmpty(AppContext.currentCityidCurrent)) {
            inJson.put("x-city-id", AppContext.currentCityidCurrent);

        }
        inJson.put("x-location-latitude", AppContext.latitude + "");
        inJson.put("x-location-longitude", AppContext.longitude + "");
        inJson.put("x-device-id", Build.SERIAL);
        inJson.put("x-client-timestamp", "15342298067" + "");
        inJson.put("x-api-ua", "pf(Android);" + "pv(" + Build.VERSION.SDK_INT + ");la(zh-CN);" + "dv(" + OSUtils.getRomType() + ");pi(" + width + "*" + height + ");ss(" + width + "*" + height + ");nm(0);nt(0);dc(" + DC_ID + ")");
        inJson.put("nonce-str", createRandom);
        inJson.put("app-distribution-channel", DC_ID);
        inJson.put("x-support-webp", "false");
        inJson.put("sign-type", "SHA256");
        if (!TextUtils.isEmpty(AppContext.getuiPushId)) {
            inJson.put("x-getui-push-id", AppContext.getuiPushId);

        }

        if (!TextUtils.isEmpty(AppContext.JPushId)) {
            inJson.put("x-jiguang-push-id", AppContext.JPushId);
        }


        //inJson.put("x-huawei-push-id", "76d8ee88646bd761f671fbff");
        // inJson.put("x-xiaomi-push-id", "76d8ee88646bd761f671fbff");

        Collection<String> keyset = inJson.keySet();

        List list = new ArrayList<String>(keyset);

        Collections.sort(list);
//这种打印出的字符串顺序和微信官网提供的字典序顺序是一致的
        for (int i = 0; i < list.size(); i++) {
            if (i < list.size() - 1) {
                signStrinf = signStrinf + list.get(i) + "=" + inJson.get(list.get(i)) + "&";

            } else {
                signStrinf = signStrinf + list.get(i) + "=" + inJson.get(list.get(i));

            }
        }
        //测试_z1zJRdJh668keWxGpBd1LYj5rCsRANJw
        //正式_bEg9VoG6TFPrjS34KCaZey8pwLUniqxd
        signStrinf = signStrinf + FORMAL_TRANSTAION;
        String token = SharedPreferencesUtil.getToken(context);
        final Request.Builder builder = new Request.Builder();

        if (!TextUtils.isEmpty(token)) {
            builder.addHeader("x-api-token", token);
        }
        if (!TextUtils.isEmpty(AppContext.getuiPushId)) {
            builder.addHeader("x-getui-push-id", AppContext.getuiPushId);

        }
        if (!TextUtils.isEmpty(AppContext.JPushId)) {
            builder.addHeader("x-jiguang-push-id", AppContext.JPushId);
        }

        if (!TextUtils.isEmpty(AppContext.currentCityidCurrent)) {
            builder.addHeader("x-city-id", AppContext.currentCityidCurrent);
        }
        Request build1 = builder.url(url).get()
                .addHeader("app-id", FORMAL_TRANSTAIONID)
                .addHeader("app-bundle-version", PhoneUtil.getAppVersion(context))
                .addHeader("app-build-version", "0")
                .addHeader("x-api-version", API_VERSION)
                /* .addHeader("x-push-id", "76d8ee88646bd761f671fbff")
                 .addHeader("x-push-type", "1")*/

                .addHeader("x-location-latitude", AppContext.latitude + "")
                .addHeader("x-location-longitude", AppContext.longitude + "")
                .addHeader("Content-Type", "application/json;charset=UTF-8")
                .addHeader("User-Agent", System.getProperty("http.agent"))
                .addHeader("Referer", "https://service.villaday.com/" + FORMAL_TRANSTAIONID + "/app/page-frame.html")
                .addHeader("x-device-id", Build.SERIAL)
                .addHeader("x-client-timestamp", "15342298067" + "")
                .addHeader("x-api-ua", "pf(Android);" + "pv(" + Build.VERSION.SDK_INT + ");la(zh-CN);" + "dv(" + OSUtils.getRomType() + ");pi(" + width + "*" + height + ");ss(" + width + "*" + height + ");nm(0);nt(0);dc(" + DC_ID + ")")
                .addHeader("nonce-str", createRandom)
                .addHeader("app-distribution-channel", DC_ID)
                .addHeader("x-support-webp", "false")
                .addHeader("sign-type", "SHA256")
                .addHeader("sign", PhoneUtil.SHA256(signStrinf).toUpperCase())
                .addHeader("Connection", "close")

                // .addHeader("x-huawei-push-id", "76d8ee88646bd761f671fbff")
                // .addHeader("x-xiaomi-push-id", "76d8ee88646bd761f671fbff")
                .build();


        if (map.size() > 0) {
            HttpUrl.Builder builder1 = build1.url().newBuilder();

            for (Map.Entry<String, String> entry : map.entrySet()) {

                if (!TextUtils.isEmpty(entry.getValue())) {
                    builder1.addQueryParameter(entry.getKey(), entry.getValue());
                }

            }
            builder.url(builder1.build());
        }

        Call call = okHttpClient.newCall(builder.build());
        call.enqueue(new OkHttpCallback(url, dataListener));
    }

    /**
     * 下载json
     */
    public static void getJSON(Context context, String url, OnDataListener dataListener) {
        OkHttpUtil.context = context;
        DisplayMetrics displayMetrics = context.getResources().getDisplayMetrics();
        int width = displayMetrics.widthPixels;
        int height = displayMetrics.heightPixels;
        Map<String, String> inJson = new HashMap<>();
        String signStrinf = "";
        String createRandom = PhoneUtil.createRandom(false, 32).toUpperCase();
        inJson.put("app-id", FORMAL_TRANSTAIONID);
        inJson.put("app-bundle-version", PhoneUtil.getAppVersion(context));
        inJson.put("app-build-version", "0");
        inJson.put("x-api-version",API_VERSION);
        /*inJson.put("x-push-id", "76d8ee88646bd761f671fbff");
        inJson.put("x-push-type", "1");*/
        if (!TextUtils.isEmpty(AppContext.currentCityidCurrent)) {
            inJson.put("x-city-id", AppContext.currentCityidCurrent);

        }
        inJson.put("x-location-latitude", AppContext.latitude + "");
        inJson.put("x-location-longitude", AppContext.longitude + "");
        inJson.put("x-device-id", Build.SERIAL);
        inJson.put("x-client-timestamp", "15342298067" + "");
        inJson.put("x-api-ua", "pf(Android);" + "pv(" + Build.VERSION.SDK_INT + ");la(zh-CN);" + "dv(" + OSUtils.getRomType() + ");pi(" + width + "*" + height + ");ss(" + width + "*" + height + ");nm(0);nt(0);dc(" + DC_ID + ")");
        inJson.put("nonce-str", createRandom);
        inJson.put("app-distribution-channel", DC_ID);
        inJson.put("x-support-webp", "false");
        inJson.put("sign-type", "SHA256");

        if (!TextUtils.isEmpty(AppContext.getuiPushId)) {
            inJson.put("x-getui-push-id", AppContext.getuiPushId);

        }

        if (!TextUtils.isEmpty(AppContext.JPushId)) {
            inJson.put("x-jiguang-push-id", AppContext.JPushId);
        }
        //  inJson.put("x-huawei-push-id", "76d8ee88646bd761f671fbff");
        // inJson.put("x-xiaomi-push-id", "76d8ee88646bd761f671fbff");


        Collection<String> keyset = inJson.keySet();

        List list = new ArrayList<String>(keyset);

        Collections.sort(list);
//这种打印出的字符串顺序和微信官网提供的字典序顺序是一致的
        for (int i = 0; i < list.size(); i++) {
            if (i < list.size() - 1) {
                signStrinf = signStrinf + list.get(i) + "=" + inJson.get(list.get(i)) + "&";

            } else {
                signStrinf = signStrinf + list.get(i) + "=" + inJson.get(list.get(i));

            }
        }
        signStrinf = signStrinf + FORMAL_TRANSTAION;
        String token = SharedPreferencesUtil.getToken(context);
        final Request.Builder builder = new Request.Builder();
        if (!TextUtils.isEmpty(token)) {
            builder.addHeader("x-api-token", token);
        }
        if (!TextUtils.isEmpty(AppContext.getuiPushId)) {
            builder.addHeader("x-getui-push-id", AppContext.getuiPushId);

        }
        if (!TextUtils.isEmpty(AppContext.JPushId)) {
            builder.addHeader("x-jiguang-push-id", AppContext.JPushId);
        }

        if (!TextUtils.isEmpty(AppContext.currentCityidCurrent)) {
            builder.addHeader("x-city-id", AppContext.currentCityidCurrent);
        }

        builder.url(url)
                .get()
                .addHeader("app-id", FORMAL_TRANSTAIONID)
                .addHeader("app-bundle-version", PhoneUtil.getAppVersion(context))
                .addHeader("app-build-version", "0")
                .addHeader("x-api-version", API_VERSION)
                /*.addHeader("x-push-id", "76d8ee88646bd761f671fbff")
                .addHeader("x-push-type", "1")*/


                .addHeader("x-location-latitude", AppContext.latitude + "")
                .addHeader("x-location-longitude", AppContext.longitude + "")
                .addHeader("Content-Type", "application/json;charset=UTF-8")
                .addHeader("User-Agent", System.getProperty("http.agent"))
                .addHeader("Referer", "https://service.villaday.com/" + FORMAL_TRANSTAIONID + "/app/page-frame.html")
                .addHeader("x-device-id", Build.SERIAL)
                .addHeader("x-client-timestamp", "15342298067" + "")
                .addHeader("x-api-ua", "pf(Android);" + "pv(" + Build.VERSION.SDK_INT + ");la(zh-CN);" + "dv(" + OSUtils.getRomType() + ");pi(" + width + "*" + height + ");ss(" + width + "*" + height + ");nm(0);nt(0);dc(" + DC_ID + ")")
                .addHeader("nonce-str", createRandom)
                .addHeader("app-distribution-channel", DC_ID)
                .addHeader("x-support-webp", "false")
                .addHeader("sign-type", "SHA256")
                .addHeader("sign", PhoneUtil.SHA256(signStrinf).toUpperCase())
                .addHeader("Connection", "close")

                // .addHeader("x-huawei-push-id", "76d8ee88646bd761f671fbff")
                //.addHeader("x-xiaomi-push-id", "76d8ee88646bd761f671fbff")
                .build();
        Call call = okHttpClient.newCall(builder.build());
        call.enqueue(new OkHttpCallback(url, dataListener));
    }

    /**
     * 同步get请求 -- 让子类调用
     */
    public static String getJSON(String url) throws IOException {
        Request request = new Request.Builder()
                .url(url)
                .build();
        Response Response = okHttpClient.newCall(request).execute();
        return Response.body().string();
    }

    /**
     * 下载小图
     */
    public static void getStream(final String url, final OnBytesListener bytesListener) {
        Request request = new Request.Builder()
                .url(url)
                .build();
        Call call = okHttpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                if (bytesListener != null) {
                    Log.e("loge", "onFailure: " + url + "\n" + e.getMessage());
                    bytesListener.onFailure(url, e.getMessage());
                }
            }

            @Override
            public void onResponse(Call call, final Response response) throws IOException {
                final byte[] bytes = response.body().bytes();
                handler.post(new Runnable() {
                    @Override
                    public void run() {
                        if (bytesListener != null) {
                            bytesListener.onResponse(url, bytes);
                        }
                    }
                });
            }
        });
    }

    /**
     * 下载文件
     */
    public static void fileDownload(final String url, final String filePath, final OnProgressListener progressListener,
                                    final OnDataListener dataListener) {
        Request request = new Request.Builder()
                .url(url)
                .build();
        Call call = okHttpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                onFail(dataListener, url, e);
            }

            @Override
            public void onResponse(Call call, final Response response) throws IOException {
                InputStream is = response.body().byteStream();
                long length = response.body().contentLength();
                OutputStream os = new FileOutputStream(new File(filePath));
                byte[] bs = new byte[1024];
                int len;
                long count = 0l;
                while ((len = is.read(bs)) != -1) {
                    count += len;
                    os.write(bs, 0, len);
                    if (count * 100 == length) {
                        progressListener.onProgress(100);

                    } else {
                        progressListener.onProgress((int) (((double) (count * 100 / length))));

                    }
                }
                is.close();
                os.close();
                onResp(dataListener, url, "suc");
            }
        });
    }

    /**
     * post提交JSON表单
     */
    public static void postJson(String url, OnDataListener dataListener) {
        final Request request = new Request.Builder()
                .url(url)
                .build();
        okHttpClient.newCall(request).enqueue(new OkHttpCallback(url, dataListener));
    }

    public static void postJson(Context context, String url, Object json, Map<String, Object> map, OnDataListener dataListener) {
        OkHttpUtil.context = context;
        String signStrinf = "";
        DisplayMetrics displayMetrics = context.getResources().getDisplayMetrics();
        int width = displayMetrics.widthPixels;
        int height = displayMetrics.heightPixels;
        MediaType JSON = MediaType.parse("application/json; charset=utf-8");
        RequestBody requestBody = RequestBody.create(JSON, gson.toJson(json));
/*
        FormBody.Builder builder = new FormBody.Builder();
        for (String in : inJson.keySet()) {
            builder.add(in, inJson.get(in));

        }*/
        //FormBody formBody = builder.build();

        String createRandom1 = PhoneUtil.createRandom(false, 32).toUpperCase();
        map.put("app-id", FORMAL_TRANSTAIONID);
        map.put("app-bundle-version", PhoneUtil.getAppVersion(context));
        map.put("app-build-version", "0");
        map.put("x-api-version", API_VERSION);
       /* map.put("x-push-id", "76d8ee88646bd761f671fbff");
        map.put("x-push-type", "1");*/

        if (!TextUtils.isEmpty(AppContext.currentCityidCurrent)) {
            map.put("x-city-id", AppContext.currentCityidCurrent);

        }

        map.put("x-location-latitude", AppContext.latitude + "");
        map.put("x-location-longitude", AppContext.longitude + "");
        map.put("x-device-id", Build.SERIAL);
        map.put("x-client-timestamp", "15342298067" + "");
        map.put("x-api-ua", "pf(Android);" + "pv(" + Build.VERSION.SDK_INT + ");la(zh-CN);" + "dv(" + OSUtils.getRomType() + ");pi(" + width + "*" + height + ");ss(" + width + "*" + height + ");nm(0);nt(0);dc(" + DC_ID + ")");
        map.put("nonce-str", createRandom1);
        map.put("app-distribution-channel", DC_ID);
        map.put("x-support-webp", "false");
        map.put("sign-type", "SHA256");
        if (!TextUtils.isEmpty(AppContext.getuiPushId)) {
            map.put("x-getui-push-id", AppContext.getuiPushId);

        }
        if (!TextUtils.isEmpty(AppContext.JPushId)) {
            map.put("x-jiguang-push-id", AppContext.JPushId);

        }


        // map.put("x-huawei-push-id", "76d8ee88646bd761f671fbff");
        //map.put("x-xiaomi-push-id", "76d8ee88646bd761f671fbff");


        Collection<String> keyset = map.keySet();

        List list = new ArrayList<String>(keyset);

        Collections.sort(list);
//这种打印出的字符串顺序和微信官网提供的字典序顺序是一致的
        for (int i = 0; i < list.size(); i++) {
            if (i < list.size() - 1) {
                signStrinf = signStrinf + list.get(i) + "=" + map.get(list.get(i)) + "&";

            } else {
                signStrinf = signStrinf + list.get(i) + "=" + map.get(list.get(i));

            }
        }
        signStrinf = signStrinf + FORMAL_TRANSTAION;
        String token = SharedPreferencesUtil.getToken(context);
        final Request.Builder builder = new Request.Builder();
        if (!TextUtils.isEmpty(token)) {
            builder.addHeader("x-api-token", token);
        }
        if (!TextUtils.isEmpty(AppContext.getuiPushId)) {
            builder.addHeader("x-getui-push-id", AppContext.getuiPushId);

        }
        if (!TextUtils.isEmpty(AppContext.JPushId)) {
            builder.addHeader("x-jiguang-push-id", AppContext.JPushId);
        }

        if (!TextUtils.isEmpty(AppContext.currentCityidCurrent)) {
            builder.addHeader("x-city-id", AppContext.currentCityidCurrent);
        }
        builder.url(url)
                .post(json == null ? okhttp3.internal.Util.EMPTY_REQUEST : requestBody)
                .addHeader("app-id", FORMAL_TRANSTAIONID)
                .addHeader("app-bundle-version", PhoneUtil.getAppVersion(context))
                .addHeader("app-build-version", "0")
                .addHeader("x-api-version", API_VERSION)
                /*  .addHeader("x-push-id", "76d8ee88646bd761f671fbff")
                  .addHeader("x-push-type", "1")*/

                .addHeader("x-location-latitude", AppContext.latitude + "")
                .addHeader("x-location-longitude", AppContext.longitude + "")
                .addHeader("Content-Type", "application/json;charset=UTF-8")
                .addHeader("User-Agent", System.getProperty("http.agent"))
                .addHeader("Referer", "https://service.villaday.com/" + FORMAL_TRANSTAIONID + "/app/page-frame.html")
                .addHeader("x-device-id", Build.SERIAL)
                .addHeader("x-client-timestamp", "15342298067" + "")
                .addHeader("x-api-ua", "pf(Android);" + "pv(" + Build.VERSION.SDK_INT + ");la(zh-CN);" + "dv(" + OSUtils.getRomType() + ");pi(" + width + "*" + height + ");ss(" + width + "*" + height + ");nm(0);nt(0);dc(" + DC_ID + ")")
                .addHeader("nonce-str", createRandom1)
                .addHeader("app-distribution-channel", DC_ID)
                .addHeader("x-support-webp", "false")
                .addHeader("sign-type", "SHA256")
                .addHeader("sign", PhoneUtil.SHA256(signStrinf).toUpperCase())
                .addHeader("Connection", "close")

                // .addHeader("x-huawei-push-id", "76d8ee88646bd761f671fbff")
                //.addHeader("x-xiaomi-push-id", "76d8ee88646bd761f671fbff")
                .build();
        okHttpClient.newCall(builder.build()).enqueue(new OkHttpCallback(url, dataListener));

    }

    public static void postJson(String url, String inJson, OnDataListener dataListener) {
        FormBody.Builder builder = new FormBody.Builder();
        builder.add("inJson", inJson);
        FormBody formBody = builder.build();

        final Request request = new Request.Builder()
                .url(url)
                .post(formBody)
                .build();
        okHttpClient.newCall(request).enqueue(new OkHttpCallback(url, dataListener));
    }

    /**
     * post提交JSON表单 -- 检查网络状态
     */
    public static void postJson(Context context, final View view, final String url, String inJson,
                                final OnDataListener dataListener) {
        OkHttpUtil.context = context;
        if (!NetworkUtil.isNetWorkEnable(context)) {//网络不可用
            final Snackbar snackbar = Snackbar.make(view, "当前网络不可用，请稍后再试", Snackbar.LENGTH_INDEFINITE);
            snackbar.setAction("确定", new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    snackbar.dismiss();
                }
            });
            Snackbar.SnackbarLayout snackBarLayout = (Snackbar.SnackbarLayout) snackbar.getView();
            snackBarLayout.setAlpha(0.8f);
            snackbar.show();
            if (view instanceof SwipeRefreshLayout) {
                view.post(new Runnable() {
                    @Override
                    public void run() {
                        ((SwipeRefreshLayout) view).setRefreshing(false);
                    }
                });
            }
        }
        postJson(url, inJson, dataListener);
    }

    /**
     * post提交Bitmap -- 不带进度条
     */
    public static void postStream(String url, String encode, Bitmap bitmap, OnDataListener dataListener) {
        postStream(url, encode, BitMapUtil.Bitmap2Bytes(bitmap), dataListener);
    }

    /**
     * post提交bytes -- 不带进度条
     */
    public static void postStream(String url, String encode, final byte[] bytes, OnDataListener dataListener) {
        RequestBody requestBody = new RequestBody() {
            @Override
            public MediaType contentType() {
                return MultipartBody.FORM;
            }

            @Override
            public long contentLength() throws IOException {
                return bytes.length;
            }

            @Override
            public void writeTo(BufferedSink sink) throws IOException {
                sink.write(bytes);
            }
        };
        createCall(encode, url, requestBody).enqueue(new OkHttpCallback(url, dataListener));
    }

    /**
     * post上传File -- 不带进度条
     */
    /*public static void postStream(String url, String encode, final File file, OnDataListener dataListener) {
        if (file == null) {
            return;
        }
        RequestBody requestBody = new RequestBody() {
            @Override
            public MediaType contentType() {
                return MultipartBody.FORM;
            }

            @Override
            public long contentLength() throws IOException {
                return file.length();
            }

            @Override
            public void writeTo(BufferedSink sink) throws IOException {
                Source source = Okio.source(file);
                sink.writeAll(source);
            }
        };
        createCall(encode, url, requestBody).enqueue(new OkHttpCallback(url, dataListener));
    }*/

    /**
     * post上传Bitmap -- 带进度条
     */
    public static void postStream(String url, String encode, final int index, Bitmap bitmap,
                                  final OnProgressMultiListener progressListener, OnDataListener dataListener) {
        final byte[] bytes = BitMapUtil.Bitmap2BAOS(bitmap).toByteArray();
        RequestBody requestBody = new RequestBody() {
            @Override
            public MediaType contentType() {
                return MultipartBody.FORM;
            }

            @Override
            public long contentLength() throws IOException {
                return bytes.length;
            }

            @Override
            public void writeTo(BufferedSink sink) throws IOException {
                Source source = Okio.source(new ByteArrayInputStream(bytes));
                long readCount = 0L;//一共上传了多少字节
                long readSize;//当前上传了多少字节
                Buffer buffer = new Buffer();
                while (true) {
                    readSize = (int) source.read(buffer, 1024);
                    if (readSize < 0) {
                        break;
                    } else {
                        sink.write(buffer, readSize);
                        readCount += readSize;
                        if (progressListener != null) {
                            int rate = (int) (readCount * 100.0 / contentLength());
                            progressListener.onProgressMulti(index, rate);
                        }
                    }
                }
            }
        };
        createCall(encode, url, requestBody).enqueue(new OkHttpCallback(url, dataListener));
    }

    /**
     * post上传File -- 带进度条
     */
    /*public static void postStream(String url, String encode, final int index, final File file,
                                  final OnProgressMultiListener progressListener, OnDataListener dataListener) {
        if (file == null) {
            return;
        }
        RequestBody requestBody = new RequestBody() {
            @Override
            public MediaType contentType() {
                return MultipartBody.FORM;
            }

            @Override
            public long contentLength() throws IOException {
                return file.length();
            }

            @Override
            public void writeTo(BufferedSink sink) throws IOException {
                Source source = Okio.source(file);
                int readCount = 0;//一共上传了多少字节
                int readSize;//当前上传了多少字节
                Buffer buffer = new Buffer();
                while(true){
                    readSize = (int) source.read(buffer, 1024);
                    if (readSize < 0) {
                        break;
                    } else {
                        sink.write(buffer, readSize);
                        readCount += readSize;
                        if (progressListener != null) {
                            int rate = (int) (readCount * 100 /contentLength());
                            progressListener.onProgressMulti(index, rate);
                        }
                    }
                }
            }
        };
        createCall(encode, url, requestBody).enqueue(new OkHttpCallback(url, dataListener));
    }*/

    /**
     * 创建Call对象
     */
    private static Call createCall(String encode, String url, RequestBody requestBody) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss", Locale.getDefault());
        String fileName = encode + "_" + sdf.format(new Date()) + ".jpg";
        MultipartBody build = new MultipartBody.Builder()
                .setType(MultipartBody.FORM)
                .addFormDataPart("EnCode", encode)
                .addPart(Headers.of("Content-Disposition", "form-data; name=\"" + encode +
                        "\"; fileName=\"" + fileName + "\""), requestBody)
                .build();
        Request request = new Request.Builder()
                .url(url)
                .post(build)
                .build();
        return okHttpClient.newCall(request);
    }

    /**
     * 结果回调
     */
    static class OkHttpCallback implements Callback {

        private String url;
        private OnDataListener dataListener;

        public OkHttpCallback(String url, OnDataListener dataListener) {
            this.url = url;
            this.dataListener = dataListener;
        }

        @Override
        public void onFailure(Call call, IOException e) {
            onFail(dataListener, url, e);
        }

        @Override
        public void onResponse(Call call, Response response) throws IOException {

            onResp(dataListener, url, response.body().string());


        }
    }

    private static void onFail(final OnDataListener dataListener, final String url, final IOException e) {
        handler.post(new Runnable() {
            @Override
            public void run() {
                try {
                    if (dataListener != null) {
                        Log.e("loge", "onFailure: " + url + "\n" + e.getMessage());
                        dataListener.onFailure(url, e.getMessage());
                    }
                } catch (Exception e) {
                    Log.e("loge", "onFailure: " + url + "\n" + e.getMessage());

                }
            }
        });
    }

    private static void onResp(final OnDataListener dataListener, final String url, final String json) {
        handler.post(new Runnable() {
            @Override
            public void run() {
                try {
                    if (dataListener != null && !TextUtils.isEmpty(json)) {
                        BaseEntity baseEntity = gson.fromJson(json, BaseEntity.class);

                        if ("101005".equals(baseEntity.getCode())) {
                            PreferencesUtil.clearData(context);
                            Intent intent = new Intent(context, LoginActivity.class);
                            intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                            context.startActivity(intent);
                        } else {
                            dataListener.onResponse(url, json);
                        }

                    }
                } catch (Exception e) {
                    Log.e("loge", json.substring(json.length() - Math.min(40, json.length())) + "\n" + "E: "
                            + e.getMessage());
                }
            }
        });
    }

    public interface OnDataListener {
        void onResponse(String url, String json);

        void onFailure(String url, String error);
    }

    public interface OnBytesListener {
        void onResponse(String url, byte[] bytes);

        void onFailure(String url, String error);
    }

    public interface OnProgressListener {
        void onProgress(int rate);
    }

    public interface OnProgressMultiListener {
        void onProgressMulti(int index, int rate);
    }
}
